/*
 *  Copyright (C) 2010 michael
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package dakside.hacc.modules.financial.exrateman;

import org.dakside.utils.DateTimeHelper;
import dakside.hacc.core.models.Currency;
import dakside.hacc.core.models.ExchangeRate;
import dakside.hacc.core.models.ExchangeRateType;
import dakside.hacc.modules.financial.currencyman.CurrencyManager;
import dakside.hacc.modules.financial.exrateman.ExchangeRateManager;
import java.util.Date;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;

/**
 *
 * @author michael
 */
public class NewExchangeRateDialog extends javax.swing.JDialog {
    /** A return status code - returned if Cancel button has been pressed */
    public static final int RET_CANCEL = 0;
    /** A return status code - returned if OK button has been pressed */
    public static final int RET_OK = 1;

    /** Creates new form NewExchangeRateDialog */
    public NewExchangeRateDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        loadNew();
        setVisible(true);
    }

    /** @return the return status of this dialog - one of RET_OK or RET_CANCEL */
    public int getReturnStatus() {
        return returnStatus;
    }

    private void loadNew(){
        try{
            ExchangeRateManager rateManager = ExchangeRateManager.getInstance();
            CurrencyManager curManager = CurrencyManager.getInstance();
            Currency[] allCur = curManager.getAllCurrency();

            //load from currency combo
            DefaultComboBoxModel modelComboFromCur = (DefaultComboBoxModel)(comboFromCurNew.getModel());
            for (Currency cur:allCur){
                modelComboFromCur.addElement(cur);
            }

            //load to currency combo
            DefaultComboBoxModel modelComboToCur = (DefaultComboBoxModel)(comboToCurNew.getModel());
            for (Currency cur:allCur){
                modelComboToCur.addElement(cur);
            }

            //load dates
            txtFromDateNew.setText(DateTimeHelper.toString(DateTimeHelper.toDateStart(new Date()),"dd/mm/yyyy HH:mm:ss"));
            txtToDateNew.setText(DateTimeHelper.toString(DateTimeHelper.toDateEnd(new Date()),"dd/mm/yyyy HH:mm:ss"));

            //load types
            DefaultComboBoxModel modelComboType = (DefaultComboBoxModel)(comboTypeNew.getModel());
            ExchangeRateType[] allTypes = rateManager.getAllExchangeRateTypes();
            for (ExchangeRateType typ:allTypes){
                modelComboType.addElement(typ);
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        comboFromCurNew = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        comboToCurNew = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        txtFromDateNew = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        txtToDateNew = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        comboTypeNew = new javax.swing.JComboBox();
        jLabel8 = new javax.swing.JLabel();
        txtRateNew = new javax.swing.JTextField();

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                closeDialog(evt);
            }
        });

        okButton.setText("Save");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 15));
        jLabel1.setText("Currency");
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText("From");
        jLabel2.setName("jLabel2"); // NOI18N

        comboFromCurNew.setName("comboFromCurNew"); // NOI18N
        comboFromCurNew.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                comboFromCurNewItemStateChanged(evt);
            }
        });
        comboFromCurNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                comboFromCurNewActionPerformed(evt);
            }
        });

        jLabel3.setText("To");
        jLabel3.setName("jLabel3"); // NOI18N

        comboToCurNew.setName("comboToCurNew"); // NOI18N

        jLabel4.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 15));
        jLabel4.setText("Validity");
        jLabel4.setName("jLabel4"); // NOI18N

        jLabel5.setText("From");
        jLabel5.setName("jLabel5"); // NOI18N

        txtFromDateNew.setText("jTextField1");
        txtFromDateNew.setName("txtFromDateNew"); // NOI18N

        jLabel6.setText("To");
        jLabel6.setName("jLabel6"); // NOI18N

        txtToDateNew.setText("jTextField2");
        txtToDateNew.setName("txtToDateNew"); // NOI18N

        jLabel7.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 15));
        jLabel7.setText("Type");
        jLabel7.setName("jLabel7"); // NOI18N

        comboTypeNew.setName("comboTypeNew"); // NOI18N

        jLabel8.setFont(new java.awt.Font("Bitstream Vera Sans", 0, 15));
        jLabel8.setText("Rate");
        jLabel8.setName("jLabel8"); // NOI18N

        txtRateNew.setText("jTextField3");
        txtRateNew.setName("txtRateNew"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel4))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(18, 18, 18)
                                .addComponent(comboFromCurNew, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(comboTypeNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtFromDateNew, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtRateNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(19, 19, 19)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addGap(18, 18, 18)
                                .addComponent(txtToDateNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(18, 18, 18)
                                .addComponent(comboToCurNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel7))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel8))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(165, 165, 165)
                        .addComponent(okButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton)))
                .addContainerGap(43, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {comboTypeNew, txtFromDateNew, txtRateNew, txtToDateNew});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelButton, okButton});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {comboFromCurNew, comboToCurNew});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(comboFromCurNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(comboToCurNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtFromDateNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(txtToDateNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(comboTypeNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(txtRateNew, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelButton)
                    .addComponent(okButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        try{
            ExchangeRateManager manager = ExchangeRateManager.getInstance();

            CurrencyManager curManager = CurrencyManager.getInstance();
            Date fromDate = DateTimeHelper.toDate(txtFromDateNew.getText().trim(), "dd/mm/yyyy HH:mm:ss");
            Date toDate = DateTimeHelper.toDate(txtToDateNew.getText().trim(), "dd/mm/yyyy HH:mm:ss");

            Currency fromCur = null;
            Object objFromCur = comboFromCurNew.getSelectedItem();
            if(objFromCur instanceof Currency){
                fromCur = (Currency)objFromCur;
            }
            Currency toCur = null;
            Object objToCur = comboToCurNew.getSelectedItem();
            if(objToCur instanceof Currency){
                toCur = (Currency)objToCur;
            }

            if(fromCur.getIsoCode().compareTo(toCur.getIsoCode()) == 0){
                JOptionPane.showMessageDialog(this,"Currencies cannot be the same","Error",JOptionPane.ERROR_MESSAGE);
                return;
            }

            ExchangeRateType type = null;
            Object objType = comboTypeNew.getSelectedItem();
            if(objType instanceof ExchangeRateType){
                type = (ExchangeRateType)objType;
            }

            double rates = Double.parseDouble(txtRateNew.getText().trim());
            ExchangeRate rate = null;
            if (fromCur != null && toCur != null && fromDate != null && toDate != null && type != null && rates > 0){
                rate = new ExchangeRate(fromCur, toCur, fromDate, toDate, rates, type);
                manager.save(rate);                
            }
            doClose(RET_OK);
        }
        catch(NumberFormatException ex){
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this,"Rate is not a valid number.","Error",JOptionPane.ERROR_MESSAGE);
        }
        catch(Exception ex){
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this,"Unable to save result.","Error",JOptionPane.ERROR_MESSAGE);
        }
        
    }//GEN-LAST:event_okButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        doClose(RET_CANCEL);
    }//GEN-LAST:event_cancelButtonActionPerformed

    /** Closes the dialog */
    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
        doClose(RET_CANCEL);
    }//GEN-LAST:event_closeDialog

    private void comboFromCurNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboFromCurNewActionPerformed
        // TODO add your handling code here:

    }//GEN-LAST:event_comboFromCurNewActionPerformed

    private void comboFromCurNewItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_comboFromCurNewItemStateChanged
        // TODO add your handling code here:
        
    }//GEN-LAST:event_comboFromCurNewItemStateChanged

    private void doClose(int retStatus) {
        returnStatus = retStatus;
        setVisible(false);
        dispose();
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                NewExchangeRateDialog dialog = new NewExchangeRateDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JComboBox comboFromCurNew;
    private javax.swing.JComboBox comboToCurNew;
    private javax.swing.JComboBox comboTypeNew;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JButton okButton;
    private javax.swing.JTextField txtFromDateNew;
    private javax.swing.JTextField txtRateNew;
    private javax.swing.JTextField txtToDateNew;
    // End of variables declaration//GEN-END:variables

    private int returnStatus = RET_CANCEL;
}
